package com.kexun.config.resolver;

import com.kexun.common.annotation.LoginManage;
import com.kexun.entity.DO.Manage;
import com.kexun.handler.ApiRRException;
import com.kexun.service.ManageService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 有@LoginManage注解的方法参数，注入当前登录用户
 *
 * @author lidong
 * @email 3275208135@qq.com
 * @date 2020-04-08
 */
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {


    private ManageService manageService;

    public LoginUserHandlerMethodArgumentResolver(ManageService userService) {
        this.manageService = userService;
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(Manage.class) && parameter.hasParameterAnnotation(LoginManage.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
        //获取用户ID
        Subject subject = SecurityUtils.getSubject();
        int userId = (int) subject.getPrincipal();
        Manage manage = manageService.findUserById(userId);
        if (manage == null) {
            subject.logout();
            throw new ApiRRException("用户不存在", 302);
        }
        return manage;
    }
}
